package com.hue.netty.day02.four;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class ServerHandler extends SimpleChannelInboundHandler<DataInfo.MyMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataInfo.MyMessage msg) throws Exception {
        DataInfo.MyMessage.DataType dataType = msg.getDataType();
        if (dataType == DataInfo.MyMessage.DataType.StudentType) {
            DataInfo.Student student = msg.getStudent();
            System.out.println("接收到student:" + "id=" + student.getId() + ",name=" + student.getName());
        } else if (dataType == DataInfo.MyMessage.DataType.TeacherType) {
            DataInfo.Teacher teacher = msg.getTeacher();
            System.out.println("接收到teacher:" + "id=" + teacher.getId() + ",name=" + teacher.getName() + ",age=" + teacher.getAge());
        } else {
            System.out.println("数据类型错误!");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将返回的数据发送写入缓存并且刷新，一般需要编码
        ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已经接收到student...", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
